#include "novelparseworker.h"

// 优化后的正则：匹配“第X章 标题”“第X章：标题”等格式，确保捕获有效内容
static const QRegularExpression chapterPattern(
        R"(^\s*第([零一二三四五六七八九十百千万\d]+章)[\s:：、]+(.*?)\s*$)",
        QRegularExpression::OptimizeOnFirstUsageOption | QRegularExpression::CaseInsensitiveOption
);

NovelParseWorker::NovelParseWorker(NovelDao *novelDao, ChapterDao *chapterDao, QObject *parent)
        : QObject(parent), m_novel_dao(novelDao), m_chapter_dao(chapterDao) {
    // 校验传入的指针是否有效（避免空指针错误）
    Q_ASSERT(novelDao != nullptr && "传入的 NovelDao 不能为空！");
    Q_ASSERT(chapterDao != nullptr && "传入的 ChapterDao 不能为空！");
}

NovelParseWorker::~NovelParseWorker() {
}

void NovelParseWorker::parseNovel(const QString &filePath, const QString &novelId) {
    qDebug() << "======》开始解析章节信息";
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "无法打开文件:" << filePath;
        return;
    }

    // 读取文件并适配编码（解决乱码问题）
    // 提前关闭，减少I/O占用
    QByteArray fileData = file.readAll();
    file.close();

    // 获取txt的具体内容
    QString content;
    if (QString::fromUtf8(fileData).isNull()) {
        content = QString::fromLocal8Bit(fileData);  // 适配中文编码
    } else {
        content = QString::fromUtf8(fileData);
    }


    //定义章节列表
    QVector < ChapterInfo * > chapters;
    qint64 currentOffset = 0;
    bool firstChapterFound = false;

    //文件存储路径
    QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QString novelChaptersDir = dataPath + "/chapters/" + novelId + "/";

    // 手动分割行（处理各种换行符）
    int pos = 0;
    const int contentSize = content.size();
    int index = 0;
    while (pos < contentSize) {
        int nextPos = content.indexOf('\n', pos);
        if (nextPos == -1) nextPos = contentSize;

        // 提取当前行（保留原始内容，不提前trim）
        QString line = content.mid(pos, nextPos - pos).trimmed();
        currentOffset = pos;  // 当前行的起始偏移

        // 正则匹配章节标题
        QRegularExpressionMatch match = chapterPattern.match(line);
        if (match.hasMatch()) {

            // 提取标题信息
            QString fullTitle = match.captured(0).trimmed();
            QString chapterNum = match.captured(1).trimmed();
            QString chapterTitle = match.captured(2).trimmed();
            if (fullTitle.isEmpty()) {
                fullTitle = chapterNum + (chapterTitle.isEmpty() ? "" : " " + chapterTitle);
            }

            // 新建当前章节
            ChapterInfo *currentChapter = new ChapterInfo();
            currentChapter->setId(MD5Util::calculateMD5({novelId, fullTitle}));
            currentChapter->setNovelId(novelId);
            currentChapter->setTitle(fullTitle);
            currentChapter->setPath(novelChaptersDir + currentChapter->getId() + ".txt");
            currentChapter->setStartOffset(currentOffset);  // 起始偏移为当前行位置
            currentChapter->setEndOffset(-1);  // 临时设为-1，最后一章会修正
            currentChapter->setChapterIndex(index);
            currentChapter->setStatus(0);
            currentChapter->setLoadStatus(0);

            // 如果不是第一个章节，更新上一个章节的endOffset
            if (firstChapterFound) {

                //更新上个章节的结束字符与章节字符数
                chapters.last()->setEndOffset(currentOffset - 1);
                chapters.last()->setWordCount(chapters.last()->getEndOffset() - chapters.last()->getStartOffset());

                //更新上个章节的next索引
                chapters.last()->setNextChapter(currentChapter->getId());
                currentChapter->setPrevChapter(chapters.last()->getId());

                qDebug() << "解析到标题：" << chapters.last()->getTitle()
                         << chapters.last()->getStartOffset()
                         << "~" << chapters.last()->getEndOffset()
                         << " 字数：" << chapters.last()->getWordCount()
                         << " 路径" << chapters.last()->getPath();
            }


            //添加章节
            chapters.append(currentChapter);

            firstChapterFound = true;
            index++;
        }

        // 移动到下一行（处理可能的\r换行符）
        pos = nextPos + 1;
        if (pos < contentSize && content.at(pos) == '\r') {
            pos++;
        }
    }

    // 关键修复：循环结束后，为最后一个章节设置endOffset（文本内容的末尾）
    if (!chapters.isEmpty()) {
        chapters.last()->setEndOffset(contentSize - 1);  // 内容总长度-1即为最后一个字符的偏移
        qDebug() << "解析到标题：" << chapters.last()->getTitle()
                 << chapters.last()->getStartOffset()
                 << "~" << chapters.last()->getEndOffset()
                 << " 路径" << chapters.last()->getPath();
    }


    //输出章节解析
    qDebug() << "章节列表解析完成";
    if (chapters.isEmpty()) {
        qWarning() << "未找到章节信息";
        return;
    }

    //章节入库
    m_chapter_dao->deleteByNovelId(novelId);
    m_chapter_dao->batchInsert(chapters);

    //打印日志
    qInfo() << "解析完成!";
    qInfo() << "总章节数:" << chapters.size();

    // 确保目录存在
    QDir dir;
    if (!dir.mkpath(novelChaptersDir)) {
        qWarning() << "无法创建章节目录:" << novelChaptersDir;
        return;
    }

    // 遍历每个章节，提取内容并保存
    for (ChapterInfo *chapter: chapters) {
        // 提取章节内容
        qint64 start = chapter->getStartOffset();
        qint64 end = chapter->getEndOffset();
        QString chapterContent = content.mid(start, end - start + 1).trimmed();

        // 生成文件名 (使用章节ID作为文件名)
        QString filePath = chapter->getPath();

        // 写入文件
        QFile chapterFile(filePath);
        if (chapterFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&chapterFile);
            out.setCodec("UTF-8");
            out << chapterContent;
            chapterFile.close();
            qDebug() << "章节内容已保存:" << filePath;
        } else {
            qWarning() << "无法写入章节文件:" << filePath;
        }
    }

    // 打印日志（保持不变）
    qInfo() << "解析完成!";
    qInfo() << "总章节数:" << chapters.size();
    qInfo() << "章节内容存储目录:" << novelChaptersDir;

    // 释放内存（保持不变）
    qDeleteAll(chapters);
    chapters.clear();
}

